/*
 * @Author: rogi
 * @Date: 2022-07-19 16:45:35
 * @LastEditTime: 2022-12-12 18:52:59
 * @LastEditors: rogi
 * @Description: 工具
 */

/**
 * @description: 数组结构(不会影响原有数组)
 * @param {String} flatList 需结构的数组
 * @param {String} key 二维数组的key
 * @return {Array} 降维之后的数组
 */
import { isRef, toRefs } from 'vue'
export const flatArray = (flatList, key) => {
  const newList = [];
  function isArr(list) {
    list.forEach(el => {
      newList.push(el)
      if (key && el[key] && el[key].length) {
        isArr(el[key])
      } else if (!key && Object.prototype.toString.call(isRef(el) ? toRefs(el) : el) === '[object Array]') {
        isArr(isRef(el) ? toRefs(el) : el)
      }
    })
  };
  isArr(flatList);
  return newList
}

/**
 * @description: 利用json表单上传组件数据 做拼接回调
 * @param {Object} file 需处理拼接的对象
 * @return {Object} 拼接后的对象
 */
export const setUploadsFormat = (file) => {
  if (Object.keys(file).length) {
    const fileObj = {}
    for (let key in file) {
      if (file[key].length) {
        if (file[key].length === 1) {
          fileObj[key] = file[key][0].url
        } else if (file[key].length > 1) {
          fileObj[key] = file[key].map(v => {
            return v.url
          })
          fileObj[key] = fileObj[key].join(',')
        }
      } else {
        fileObj[key] = ''
      }
    }
    return fileObj
  }
}

/**
 * @description: 根据接口返回的图片拼接数据 转成json数组格式
 * @param {Object} fileObj 需处理拼接的对象 使用方式getUploadsFormat({ 图片name: "url,url" })多张用,分割
 * @return {Object} 格式化为json渲染格式后
 */
export const getUploadsFormat = (fileObj) => {
  const file = {}
  for (let key in fileObj) {
    if (fileObj[key]) {
      file[key] = []
      console.log('keykey', key)
      const arr = fileObj[key].split(',')
      file[key] = arr.map(v => {
        return { url: v }
      })
    } else if (fileObj[key] == '') {
      file[key] = []
    }

  }
  return file
}

/**
 * @description: 生成GUID
 * @return {*} UID
 */
export const createGuid = () => {
  return 'xxxxxxxxxxxxxxxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : r & 0x3 | 0x8;
    return v.toString(16);
  });
}

/**
 * @description: 通过身份证号获取出生日期
 * @param {String} value
 * @return {*}
 */
 export const idbirthdate = (value) => {
  let birthday = '';
  if (value != null && value != '') {
    if (value.length == 15) {
      birthday = '19' + value.slice(6, 12);
    } else if (value.length == 18) {
      birthday = value.slice(6, 14);
    }

    return birthday.replace(/(.{4})(.{2})/, '$1-$2-');
  }
}

/**
 * @description: 数字小写转大写
 * @param {*} money
 * @return {*}
 */
export const toBigNumber = (money) => {
  //形参
  // 汉字的数字
  const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  // 基本单位
  const cnIntRadice = ['', '拾', '佰', '仟']
  // 对应整数部分扩展单位
  const cnIntUnits = ['', '万', '亿', '兆']
  // 对应小数部分单位
  const cnDecUnits = ['角', '分']
  // 整数金额时后面跟的字符
  const cnInteger = '整'
  // 整型完以后的单位
  const cnIntLast = '元'
  // 最大处理的数字
  const maxNum = 9999999999999999.99
  // 金额整数部分
  let integerNum
  // 金额小数部分
  let decimalNum
  // 输出的中文金额字符串
  let chineseStr = ''
  // 分离金额后用的数组，预定义
  let parts
  if (money === '') {
    return ''
  }
  money = parseFloat(money)
  if (money >= maxNum) {
    // 超出最大处理数字
    return ''
  }
  if (money === 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }
  // 转换为字符串
  money = money.toString()
  if (money.indexOf('.') === -1) {
    integerNum = money

    decimalNum = ''
  } else {
    parts = money.split('.')
    integerNum = parts[0]
    decimalNum = parts[1].substr(0, 4)
  }
  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0
    const IntLen = integerNum.length
    for (let i = 0; i < IntLen; i++) {
      const n = integerNum.substr(i, 1)
      const p = IntLen - i - 1
      const q = p / 4
      const m = p % 4
      if (n === '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        // 归零
        zeroCount = 0
        //alert(cnNums[parseInt(n)])
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    chineseStr += cnIntLast
  }
  // 小数部分
  if (decimalNum !== '') {
    const decLen = decimalNum.length
    for (let i = 0; i < decLen; i++) {
      const n = decimalNum.substr(i, 1)
      if (n !== '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (chineseStr === '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum === '') {
    chineseStr += cnInteger
  }
  return chineseStr
}

export const getAddress = (code = '440111', type = 'text') => {
  const res = flatArray(JSON.parse(localStorage.getItem('area')), 'children');
  const address = []
  function resForEach(id) {
    res.forEach(el => {
      if (el.id === id) {
        address.unshift(el)
        resForEach(el.pid)
      }
    })
  }
  resForEach(code)
  const typeFunction = {
    text: () => {
      if (address && !address.length) {
        return code
      }
      return address.map(el => el.name).join('/')
    }
  }
  return typeFunction[type]()
  // console.log('resres', address)
}

/**
 * @description: 分页闭包，用于滚动加载更多
 * @param {*} pageNo 当前分页
 * @param {*} pageSize 每页多少个
 * @return {*}
 */
export const scrollPaging = (pageNo = 1, pageSize = 20) => {
  const backups = {
    pageNo,
    pageSize
  }
  return {
    /**
     * @description: 重置，通过首次初始化备份的pageNo与pageSize进行重置，如需重置不需要重新初始化
     * @return {*}
     */    
    reset: function() {
      pageNo = backups.pageNo
      pageSize = backups.pageSize
    },
    /**
     * @description: 下一页
     * @param {*} totalPage 总页数，既每次调用这个方法的时候，需要传递总页数进行最大值匹配
     * @return {*} Object type: maxPage = 最大值了，不能进行下一页了
     */    
    nextPage: function (totalPage) {
      if (pageNo >= totalPage) {
        return { type: "maxPage" }
      }
      pageNo++
      return { type: 'loading' }
    },
    /**
     * @description: 上一页，一般用不到
     * @return {*}
     */    
    previousPage: function() {
      pageNo--
    },
    /**
     * @description: 这里返回当前页数和分页值
     * @return {*}
     */    
    pageData: function() {
      return {
        pageSize,
        pageNo
      }
    }
  }
}

/**
 * @description: 防抖
 * @param {*} callback 回调
 * @param {*} wait 防抖时间
 * @return {*}
 */
export function debounce(callback, wait = 700) {
  let timer;
    return function () {
      let context = this;
      let args = arguments;
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        callback.apply(context, args);
      }, wait)
    }
}

export const getQueryStrings = (url) => {
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
     var str = url.substr(1);
     let strs = str.split("&");
     for(var i = 0; i < strs.length; i ++) {
        theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
     }
  }
  return theRequest;
}

export const checkBtn = (btnConfig) => {
  if (!btnConfig) {
    return false
  }
  if (btnConfig && btnConfig.hidePath === 0) {
    return true
  }
  return false
}